/*
 * @Author: 1960116313@qq.com 1960116313@qq.com
 * @Date: 2023-10-23 14:13:58
 * @LastEditors: 1960116313@qq.com 1960116313@qq.com
 * @LastEditTime: 2023-10-24 15:43:12
 * @FilePath: \panuniapp\src\store\user\user.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { defineStore } from "pinia";
import cache from "@/utils/cache";
import { TOKEN_KEY, USER_INFO } from "@/utils/constantEnums";
import { Login } from "@/api/user";
export const userStore = defineStore("useUserStore", {
  state: () => ({
    userInfo: cache.get(USER_INFO) || null,
    // 后端token时效是：604800s = 7天
    accessToken: cache.get(TOKEN_KEY) || null,
    refreshToken: null,
  }),
  getters: {
    isLogin: (state) => !!state.accessToken, //是否登录
    getUserInfo: (state) => state.userInfo, //个人信息
  },
  actions: {
    // 登录
    async login(params) {
      const res = await Login(params);
      //登陆后返回的值
      this.accessToken = res.data.access_token;
      this.refreshToken = res.refresh_token;
      cache.set(TOKEN_KEY, res.data.access_token);
      this.setUserInfo(res.data);
    },
    logout() {
      this.accessToken = null;
      this.userInfo = {};
      cache.remove(TOKEN_KEY);
      cache.remove(USER_INFO);
    },
    setUserInfo(info) {
      this.userInfo = info;
      cache.set(USER_INFO, info);
    },
  },
});
